package com.bawei.module_home.http

import android.os.Build
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.annotation.RequiresApi
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.arouter.utils.TextUtils
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.RequestEvent
import com.bawei.lib_common.base.state.Success
import com.bawei.module_home.R
import com.bawei.module_home.model.AddMerchantBody
import com.bawei.module_home.model.AreaDetailModel
import com.bawei.module_home.model.AreaModel
import com.bawei.module_home.model.AreaModelItem
import com.bawei.module_home.model.DeviceModel
import com.bawei.module_home.model.HomeServiceModel
import com.bawei.module_home.model.MerchantModel
import com.bawei.module_home.model.MerchantModelItem
import com.bawei.module_home.model.HouseItem
import com.bawei.module_home.model.NewsBody
import com.bawei.module_home.model.NewsModelItem
import com.bawei.module_home.model.NoticeModelItem
import com.bawei.module_home.model.ProfilesModelItem
import com.bawei.module_home.model.RepairModel
import com.bawei.module_home.model.SignParam
import com.bawei.module_home.model.SignResult
import com.bawei.module_home.model.StatusModel
import com.bawei.module_home.model.VipModel
import com.bawei.module_home.model.VisitorBody
import com.bawei.module_home.model.VisitorData
import com.bawei.module_home.model.VisitorListData
import com.bawei.module_home.model.addAreaBody
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Calendar
import java.util.Locale
import javax.inject.Inject

@HiltViewModel
class HomeServiceViewModel @Inject constructor(private val repository: HomeServiceRepository):BaseViewModel() {

    val ServiceList= mutableListOf<HomeServiceModel>()
    val noticeList= mutableListOf<NoticeModelItem>()
    var areaList = mutableListOf<AreaModelItem>()
    var houseList= mutableListOf<HouseItem>()
    var houseList2= mutableListOf<HouseItem>()
    var areaNewList=mutableListOf<AreaModelItem>()
    val vipUser= MutableLiveData<VipModel>()
    val deviceList = mutableListOf<DeviceModel>()
    val proFilesList = mutableListOf<ProfilesModelItem>()
    val newProFilesList = mutableListOf<ProfilesModelItem>()
    val merchantList = mutableListOf<MerchantModelItem>()
    val merchantAList=mutableListOf<MerchantModelItem>()
    val merchantBList=mutableListOf<MerchantModelItem>()
    val visitorList=mutableListOf<VisitorListData>()
    val newMerchantList = mutableListOf<MerchantModelItem>()
    val signList = mutableListOf<SignResult>()
    val newsList=mutableListOf<NewsModelItem>()
    val newsNewList=mutableListOf<NewsModelItem>()

    val merchantDetailItem = MutableLiveData<MerchantModelItem>()
    //会员更新
    val updateVip=  MutableLiveData<VipModel>()

    val detailItem = MutableLiveData<AreaDetailModel>()

    val deviceDetail = MutableLiveData<DeviceModel>()

    val deviceStatus = MutableLiveData<String>()

    val areaDetailItem = MutableLiveData<AreaDetailModel>()

    val profileDetailItem= MutableLiveData<ProfilesModelItem>()





    //公告
    private val _mNotice=MutableStateFlow<RequestEvent>(Loading)
    val noticeState
        get() =_mNotice.asStateFlow()

    private val _mArea= MutableStateFlow<RequestEvent>(Loading)
    val areaState
        get() = _mArea.asStateFlow()

    private val _addArea= MutableStateFlow<RequestEvent>(Loading)
    val addAreaState
        get() = _addArea.asStateFlow()

    private val _deleteArea= MutableStateFlow<RequestEvent>(Loading)
    val deleteAreaState
        get() = _deleteArea.asStateFlow()

    private val _detailArea= MutableStateFlow<RequestEvent>(Loading)
    val detailAreaState
        get() = _detailArea.asStateFlow()

    private val _mVip=MutableStateFlow<RequestEvent>(Loading)
    val vipState
        get() = _mVip.asStateFlow()

    private val _mDevice=MutableStateFlow<RequestEvent>(Loading)
    val deviceState
        get() = _mDevice.asStateFlow()

    private val _mUpdateVip=MutableStateFlow<RequestEvent>(Loading)
    val updateVipState
        get() = _mUpdateVip.asStateFlow()

    private val _mMerchant=MutableStateFlow<RequestEvent>(Loading)
    val _mMerchantState
        get() = _mMerchant.asStateFlow()

    private val _mAddMerchant=MutableStateFlow<RequestEvent>(Loading)
    val _mAddMerchantState
        get() = _mAddMerchant.asStateFlow()

    private val _mApproveMerchant=MutableStateFlow<RequestEvent>(Loading)
    val _mApproveMerchantState
        get() = _mApproveMerchant.asStateFlow()
    //物业报修
    private val _mRepair=MutableStateFlow<RequestEvent>(Loading)
    val repairState
        get() = _mRepair.asStateFlow()

    private val _mAddDevice=MutableStateFlow<RequestEvent>(Loading)
    val addDeviceState
        get() = _mAddDevice.asStateFlow()
    private val _mDeviceDetail=MutableStateFlow<RequestEvent>(Loading)
    val deviceDetailState
        get() = _mDeviceDetail.asStateFlow()
    private val _mDeviceStatus=MutableStateFlow<RequestEvent>(Loading)
    val deviceStatusState
        get() = _mDeviceStatus.asStateFlow()
    private val _mDeleteDevice=MutableStateFlow<RequestEvent>(Loading)
    val deleteDeviceState
        get() = _mDeleteDevice.asStateFlow()

    private val _merchantDetail= MutableStateFlow<RequestEvent>(Loading)
    val merchantDetailState
        get() = _merchantDetail.asStateFlow()

    private val _mVisitor=MutableStateFlow<RequestEvent>(Loading)
    val addVisitor
        get() = _mVisitor.asStateFlow()

    private val _mVisitorList=MutableStateFlow<RequestEvent>(Loading)
    val getVisitorList
        get() = _mVisitorList.asStateFlow()

    private val _mSigns=MutableStateFlow<RequestEvent>(Loading)
    val signsState
        get() = _mSigns.asStateFlow()
    private val _mProfiles= MutableStateFlow<RequestEvent>(Loading)
    val  mProfilesState
        get()=_mProfiles.asStateFlow()

    private val _mProFilesDetail= MutableStateFlow<RequestEvent>(Loading)
    val mProfilesDetailState
        get() = _mProFilesDetail.asStateFlow()

    //获取房源信息
    private val _mHouse=MutableStateFlow<RequestEvent>(Loading)
    val houseState
        get() = _mHouse.asStateFlow()
    //获取小区信息
    private val _mHouse2=MutableStateFlow<RequestEvent>(Loading)
    val houseState2
        get() = _mHouse2.asStateFlow()
    //获取公告
    private val _news= MutableStateFlow<RequestEvent>(Loading)
    val newsState
        get() = _news.asStateFlow()

    private val _sendNews= MutableStateFlow<RequestEvent>(Loading)
    val _sendNewsState
        get() = _sendNews.asStateFlow()



    //计算到期日期
    @RequiresApi(Build.VERSION_CODES.O)
    fun calculateDueDate(starDatetStr: String, daysToAdd: Int): String {
        //解析办理日期
        val formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd")
        val starDate= LocalDate.parse(starDatetStr,formatter)

        //计算到期日期
        val expireDate=starDate.plusDays(daysToAdd.toLong())

        //格式化日期
        return formatter.format(expireDate)

    }
    //判断是不是到期
    @RequiresApi(Build.VERSION_CODES.O)
    fun isExpire(expireDate: String): Boolean {
        val dateFormat= SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val dueDate=dateFormat.parse(expireDate)!!
        val currentDate= Calendar.getInstance().time//当前时间
        return currentDate.after(dueDate)//判断当前时间是否在到期时间之后
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun getDataTime():String{
        //到期时间
        val endData=calculateDueDate(vipUser.value!!.registrationDate,vipUser.value!!.duration)
        return if(isExpire(endData)){
            "已到期"
        }else{
            endData+"到期"
        }
    }



    fun initList(){
        ServiceList.add(HomeServiceModel(R.mipmap.img1,"车位管理"))
        ServiceList.add(HomeServiceModel(R.mipmap.img2,"访客登记"))
        ServiceList.add(HomeServiceModel(R.mipmap.img3,"物业报修"))
        ServiceList.add(HomeServiceModel(R.mipmap.img4,"考勤打卡"))
        ServiceList.add(HomeServiceModel(R.mipmap.img5,"房源信息"))
        ServiceList.add(HomeServiceModel(R.mipmap.img6,"商家推荐"))
        ServiceList.add(HomeServiceModel(R.mipmap.img7,"月卡会员"))
        ServiceList.add(HomeServiceModel(R.mipmap.img8,"设备管理"))


    }
    //获取公告
    fun getNotice(page:Int,size:Int){
        execute(
            action = repository.getNotice(page,size),
            onStart = {
                _mNotice.value=Loading
            },
            onError = {
                _mNotice.value=Failed(it)
            },
            onFinish = {
                noticeList.clear()
                noticeList.addAll(it.data)
                _mNotice.value=Success
            }
        )
    }

    fun getArea(areaId: Int){
        execute(
            action = repository.getArea(areaId),
            onStart = {
                _mArea.value= Loading
            },
            onError = {
                _mArea.value= Failed(it)
            },
            onFinish = {
                areaList.clear()
                areaList.addAll(it.data)
                areaList.reverse()
                _mArea.value= Success
            }
        )
    }

    fun addArea(body: addAreaBody){
        execute(
            action = repository.addArea(body),
            onStart = {
                _mArea.value= Loading
            },
            onError = {
                _mArea.value= Failed(it)
            },
            onFinish = {
                _mArea.value= Success
            }
        )
    }

    //获取会员
    fun getVip(userId:Int){
        executeTS(
            action = repository.getVip(userId),
            onStart = {
                _mVip.value=Loading
            },
            onError = {
                _mVip.value=Failed("失败"+it)
                Log.d("YJK", "getVip:失败")
            },
            onFinish = {
                vipUser.value=it
                Log.d("YJK", "getVip:成功")
                _mVip.value=Success
            }
        )
    }

    //获取设备
    fun getDeviceList(){
        execute(
            action = repository.getDeviceList(),
            onStart = {
                _mDevice.value=Loading
            },
            onError = {
                _mDevice.value=Failed(it)
            },
            onFinish = {
                deviceList.clear()
                deviceList.addAll(it.data)
                _mDevice.value=Success
            }
        )
    }

    //会员升级
    fun put_upgrade(userId:Int,newMembershipLevel:String){
        executeTS(
            action = repository.put_upgrade(userId,newMembershipLevel),
            onStart = {
                _mUpdateVip.value=Loading
            },
            onError = {
                _mUpdateVip.value=Failed("失败"+it)
            },
            onFinish = {
                updateVip.value=it
                _mUpdateVip.value=Success
            }
        )
    }


    fun deleteArea(id: Int){
        execute(
            action = repository.deleteArea(id),
            onStart = {
                _deleteArea.value=Loading
            },
            onError = {
                _deleteArea.value=Failed(it)
            },
            onFinish = {
                _deleteArea.value=Success
            }
        )
    }

    fun AreaDetail(id: Int){
        execute(
            action = repository.areaDetail(id),
            onStart = {
                _detailArea.value=Loading
            },
            onError = {
                _detailArea.value=Failed(it)
            },
            onFinish = {
                areaDetailItem.value=it.data
                _detailArea.value=Success
            }
        )
    }

    fun merchant(){
        execute(
            action = repository.merchant(),
            onStart = {
                _mMerchant.value=Loading
            },
            onError = {
                _mMerchant.value=Failed(it)
            },
            onFinish = {
                merchantList.clear()
                merchantList.addAll(it.data)
                merchantAList.addAll(merchantList.filter { it.status=="新建" })
                merchantBList.addAll(merchantList.filter { it.status=="已审核" })
                _mMerchant.value= Success
            }
        )
    }

    fun addMerchant(body: AddMerchantBody){
        execute(
            action = repository.addMerchant(body),
            onStart = {
                _mAddMerchant.value=Loading
            },
            onError = {
                _mAddMerchant.value=Failed(it)
            },
            onFinish = {
                _mAddMerchant.value=Success
            }
        )
    }

    fun getMerchantDetail(id: Int){
        execute(
            action = repository.merchantDetail(id),
            onStart = {
                _merchantDetail.value=Loading
            },
            onError = {
                _merchantDetail.value=Failed(it)
            },
            onFinish = {
                merchantDetailItem.value=it.data
                _merchantDetail.value= Success
            }
        )
    }

    fun approveMerchant(id: Int){
        execute(
            action = repository.approveMerchant(id),
            onStart = {
                _mApproveMerchant.value=Loading
            },
            onError = {
                _mApproveMerchant.value=Failed(it)
            },
            onFinish = {
                _mApproveMerchant.value=Success
            }
        )
    }


    fun getProfiles(){
        execute(
            action = repository.getProfiles(),
            onStart = {
                _mProfiles.value=Loading
            },
            onError = {
                _mProfiles.value=Failed(it)
            },
            onFinish = {
                proFilesList.clear()
                proFilesList.addAll(it.data)
                _mProfiles.value=Success
            }
        )
    }

    fun getProfilesDetail(id: Int){
        execute(
            action = repository.getProfilesDetail(id),
            onStart = {
                _mProFilesDetail.value=Loading
            },
            onError = {
                _mProFilesDetail.value=Failed(it)
            },
            onFinish = {
                profileDetailItem.value=it.data
                _mProFilesDetail.value=Success
            }
        )
    }



    //新增设备
    fun insertDevice(body: DeviceModel){
        execute(
            action = repository.insertDevice(body),
            onStart = {
                _mAddDevice.value=Loading
            },
            onError = {
                _mAddDevice.value=Failed(it)
            },
            onFinish = {
                _mAddDevice.value=Success
            }
        )
    }
    //设备详情
    fun getDeviceDetail(id:Int){
        execute(
            action = repository.getDeviceDetail(id),
            onStart = {
                _mDeviceDetail.value=Loading
            },
            onError = {
                _mDeviceDetail.value=Failed(it)
            },
            onFinish = {
                deviceDetail.value=it.data
                _mDeviceDetail.value=Success
            }
        )
    }

    //报修
    fun postRepair(body: RepairModel){
        execute(
            action = repository.postRepair(body),
            onStart = {
                _mRepair.value=Loading
            },
            onError = {
                _mRepair.value=Failed(it)
            },
            onFinish = {
                _mRepair.value=Success
            }
        )
    }
    //设备状态
    fun postDeviceStatus(id: Int,status: String){
        execute(
            action = repository.postDeviceStatus(id,status),
            onStart = {
                _mDeviceStatus.value=Loading
            },
            onError = {
                _mDeviceStatus.value=Failed(it)
            },
            onFinish = {
                deviceStatus.value=it.data.status
                _mDeviceStatus.value=Success
            }
        )
    }
    //删除设备
    fun deleteDevice(id: Int){
        execute(
            action = repository.deleteDevice(id),
            onStart = {
                _mDeleteDevice.value=Loading
            },
            onError = {
                _mDeleteDevice.value=Failed(it)
            },
            onFinish = {
                if (it.data){
                    _mDeleteDevice.value=Success
                }
            }
        )
    }
    //来访登记
    fun addVisitor(body: VisitorBody){
        execute(
            action = repository.addVisitor(body),
            onStart = {
                _mVisitor.value= Loading
            },
            onError = {
                _mVisitor.value= Failed(it)
            },
            onFinish = {
                _mVisitor.value= Success
//                ARouter.getInstance().build(Router.MAIN_PAGE).navigation()
            }
        )
    }
    //获取来访列表
    fun getVisitor(){
        execute(
            action = repository.getVisitor(),
            onStart = {
                _mProfiles.value=Loading
            },
            onError = {
                _mProfiles.value=Failed(it)
            },
            onFinish = {
                visitorList.clear()

                visitorList.addAll(it.data)
                visitorList.reverse()
                _mVisitorList.value=Success
            }
        )
    }



    fun getSignList(userId: Int){
        execute(
            action = repository.getSignList(userId),
            onStart = {
                _mSigns.value=Loading
            },
            onError = {
                _mSigns.value=Failed(it)
            },
            onFinish = {
                signList.clear()
                signList.addAll(it.data)
                _mSigns.value=Success
            }
        )
    }

    //获取所有房源信息
    fun getAllHouse(){
        execute(
            action = repository.getAllHouse(),
            onStart = {
                _mHouse.value=Loading
            },
            onError = {
                _mHouse.value=Failed(it)
            },
            onFinish = {
                houseList.clear()
                houseList.addAll(it.data)
                _mHouse.value=Success

            }
        )

    }
    fun getHouse2(regionId:Int){
        execute(
            action = repository.getHouse2(regionId),
            onStart = {
                _mHouse2.value=Loading
            },
            onError = {
                _mHouse2.value=Failed(it)
            },
            onFinish = {
                houseList2.clear()
                houseList2.addAll(it.data)
                _mHouse2.value=Success
            }
        )
    }

    fun getNews(){
        execute(
            action = repository.getNews(),
            onStart = {
                _news.value= Loading
            },
            onError = {
                _news.value= Failed(it)
            },
            onFinish = {
                newsList.clear()
                newsList.addAll(it.data)
                _news.value= Success
            }
        )
    }

    fun sendNews(body: NewsBody){
        execute(
            action = repository.sendNews(body),
            onStart = {
                _sendNews.value= Loading
            },
            onError = {
                _sendNews.value= Failed(it)
            },
            onFinish = {
                _sendNews.value= Success
            }
        )
    }

}